#!/bin/bash
# CentOS 7 静态编译脚本 - 解决 libprotobuf.so.15 依赖问题

set -e

echo "========================================="
echo "moparse CentOS 7 静态编译脚本"
echo "========================================="
echo ""

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 获取脚本所在目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

echo "问题描述："
echo "  在 CentOS 7 上运行 moparse 时出现："
echo "  error while loading shared libraries: libprotobuf.so.15: cannot open shared object file"
echo ""
echo "解决方案："
echo "  1. 使用 Rust 版本 musl 静态编译（推荐）✨"
echo "  2. 使用 C++ 完全静态编译（需要静态库）"
echo ""

# 检查是否有 Rust
if command -v cargo &> /dev/null; then
    HAS_RUST=1
    print_info "检测到 Rust 环境: $(rustc --version)"
else
    HAS_RUST=0
    print_warn "未检测到 Rust 环境"
fi

# 检查是否有静态 protobuf 库
if [ -f "/usr/lib64/libprotobuf.a" ] || [ -f "/usr/lib/libprotobuf.a" ]; then
    HAS_STATIC_PROTOBUF=1
    print_info "检测到静态 protobuf 库"
else
    HAS_STATIC_PROTOBUF=0
    print_warn "未检测到静态 protobuf 库"
fi

echo ""
echo "可用的编译方案："
echo ""

if [ $HAS_RUST -eq 1 ]; then
    echo -e "${GREEN}[推荐]${NC} 方案 1: Rust musl 静态编译"
    echo "  - 完全静态链接，零系统库依赖"
    echo "  - 可在任何 Linux 发行版运行"
    echo "  - 命令: ./build_static_centos7.sh rust"
    echo ""
fi

if [ $HAS_STATIC_PROTOBUF -eq 1 ]; then
    echo -e "${GREEN}[可用]${NC} 方案 2: C++ 完全静态编译"
    echo "  - 静态链接所有库"
    echo "  - 命令: ./build_static_centos7.sh cpp-full"
    echo ""
else
    echo -e "${YELLOW}[不可用]${NC} 方案 2: C++ 完全静态编译"
    echo "  - 需要安装静态 protobuf 库"
    echo "  - 安装: sudo yum install protobuf-static -y"
    echo ""
fi

echo -e "${BLUE}[备选]${NC} 方案 3: C++ 尝试静态链接"
echo "  - 尽可能静态链接（可能仍有少量依赖）"
echo "  - 命令: ./build_static_centos7.sh cpp-try"
echo ""

# 解析命令行参数
METHOD=${1:-""}

if [ -z "$METHOD" ]; then
    # 自动选择最佳方案
    if [ $HAS_RUST -eq 1 ]; then
        METHOD="rust"
        print_info "自动选择方案 1: Rust musl 静态编译"
    elif [ $HAS_STATIC_PROTOBUF -eq 1 ]; then
        METHOD="cpp-full"
        print_info "自动选择方案 2: C++ 完全静态编译"
    else
        METHOD="cpp-try"
        print_warn "自动选择方案 3: C++ 尝试静态链接（可能仍有依赖）"
    fi
fi

echo ""
echo "========================================="
echo "开始编译: $METHOD"
echo "========================================="
echo ""

case $METHOD in
    rust)
        if [ $HAS_RUST -eq 0 ]; then
            print_error "Rust 未安装，请先安装 Rust:"
            echo "  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
            exit 1
        fi
        
        print_step "1/5 进入 Rust 项目目录"
        cd moparse-rs
        
        print_step "2/5 检查 musl 目标"
        if ! rustup target list | grep -q "x86_64-unknown-linux-musl (installed)"; then
            print_info "安装 musl 目标..."
            rustup target add x86_64-unknown-linux-musl
        fi
        
        print_step "3/5 清理旧版本"
        cargo clean
        
        print_step "4/5 开始编译（musl 静态链接）"
        export RUSTFLAGS="-C target-feature=+crt-static -C link-arg=-static"
        cargo build --release --target=x86_64-unknown-linux-musl
        
        BINARY="target/x86_64-unknown-linux-musl/release/moparse"
        
        print_step "5/5 验证编译结果"
        if [ -f "$BINARY" ]; then
            print_info "编译成功！"
            echo ""
            echo "二进制文件: $BINARY"
            ls -lh "$BINARY"
            echo ""
            
            # 检查依赖
            print_info "依赖检查:"
            if ldd "$BINARY" 2>&1 | grep -q "not a dynamic executable"; then
                print_info "✅ 完全静态链接，无动态库依赖"
            else
                print_warn "⚠️  仍有动态库依赖:"
                ldd "$BINARY"
            fi
            
            # 复制到上级目录
            print_info "复制到 modb 目录..."
            cp "$BINARY" ../moparse-static
            
            echo ""
            print_info "使用方法:"
            echo "  cd .."
            echo "  ./moparse-static -h"
            
        else
            print_error "编译失败！"
            exit 1
        fi
        ;;
        
    cpp-full)
        if [ $HAS_STATIC_PROTOBUF -eq 0 ]; then
            print_error "未找到静态 protobuf 库，请先安装:"
            echo "  sudo yum install protobuf-static -y"
            exit 1
        fi
        
        print_step "1/3 清理旧版本"
        make clean
        
        print_step "2/3 完全静态编译"
        make static-full
        
        print_step "3/3 验证编译结果"
        if [ -f "moparse" ]; then
            print_info "编译成功！"
            echo ""
            ls -lh moparse
            echo ""
            
            print_info "依赖检查:"
            ldd moparse || print_info "✅ 完全静态链接"
        else
            print_error "编译失败！"
            exit 1
        fi
        ;;
        
    cpp-try)
        print_step "1/3 清理旧版本"
        make clean
        
        print_step "2/3 尝试静态链接"
        make static-try || {
            print_warn "static-try 失败，尝试 static-full..."
            make static-full || {
                print_error "编译失败！建议使用 Rust musl 方案"
                exit 1
            }
        }
        
        print_step "3/3 验证编译结果"
        if [ -f "moparse" ]; then
            print_info "编译成功！"
            echo ""
            ls -lh moparse
            echo ""
            
            print_info "依赖检查:"
            ldd moparse
            
            DEP_COUNT=$(ldd moparse 2>&1 | grep "=>" | wc -l)
            if [ $DEP_COUNT -le 3 ]; then
                print_info "✅ 依赖较少 ($DEP_COUNT 个)"
            else
                print_warn "⚠️  仍有 $DEP_COUNT 个动态库依赖"
                print_warn "建议使用 Rust musl 方案获得完全静态链接"
            fi
        else
            print_error "编译失败！"
            exit 1
        fi
        ;;
        
    *)
        print_error "未知的编译方案: $METHOD"
        echo "可用选项: rust, cpp-full, cpp-try"
        exit 1
        ;;
esac

echo ""
echo "========================================="
echo "编译完成！"
echo "========================================="
echo ""

if [ "$METHOD" = "rust" ]; then
    echo "推荐使用 Rust 静态版本:"
    echo "  ./moparse-static -h"
    echo ""
    echo "或使用完整路径:"
    echo "  ./moparse-rs/target/x86_64-unknown-linux-musl/release/moparse -h"
else
    echo "使用 C++ 版本:"
    echo "  ./moparse -h"
fi

echo ""
echo "如果在 CentOS 7 上仍有问题，请使用 Rust musl 方案："
echo "  ./build_static_centos7.sh rust"
